import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/Login'
import Register from '@/views/Register'
import Detail from '@/views/Detail'
import Layout from '@/views/Layout'

import Like from '@/views/Like'
import Article from '@/views/Article'
import Collect from '@/views/Collect'
import User from '@/views/User'
import About from '@/views/About'
import Suggest from '@/views/Suggest'

import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/article' },
    { path: '/register', component: Register },
    { path: '/login', component: Login },
    { path: '/detail/:id', component: Detail },
    { path: '/aboutus', component: About },
    { path: '/suggestpage', component: Suggest },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/article', component: Article },
        { path: '/collect', component: Collect },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    }
  ]
})

const whiteList = ['/login', '/register']
// 导航守卫
router.beforeEach((to, form, next) => {
  const token = getToken()
  console.log(token)
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('您还未登录, 请登录')
      next('/login')
    }
  }
})

export default router
